<script lang="ts" setup>
import useModal from '@/hooks/useModal'
import cloneDeep from 'lodash/cloneDeep'
import SelectUploadList from '@/components/upload/SelectUploadList.vue'
import SelectProductList from '@/components/SelectModal/Product.vue'
import SelectSellerList from '@/components/SelectModal/Seller.vue'
import SelectCommunityList from '@/components/SelectModal/Community.vue'
import SelectActivityList from '@/components/SelectModal/Activity.vue'
import PageLink from '@/components/Modal/PageLink.vue'
import { getToken } from '@/utils/auth'
const route = useRoute()
const iframeRef = ref<any>()
const { store } = useModal()
const list = ref<any[]>([])
const bindOptions = reactive<any>({ data: {} })
const postMessageType = ref('' as PostMessageType)
const postMessageCallback = ({ data }) => {
  const { type, options } = data as PostMessage
  Object.assign(bindOptions, options)
  postMessageType.value = type
  store.handleShow({})
}
const sendPostMessage = (sendData: SendPostMessage) => {
  iframeRef.value.contentWindow.postMessage(sendData, '*')
}
console.log(import.meta.env)

const iframeUrl = computed(() => `${location.origin}${import.meta.env.VITE_DIY_URL}?id=${route.query.id}&token=${getToken()}`)

/**判断消息类型弹出指定组件 */
const cmp = computed(() => {
  switch (postMessageType.value) {
    case 'upload':
      return SelectUploadList
    case 'product':
      return SelectProductList
    case 'seller':
      return SelectSellerList
    case 'activity':
      return SelectActivityList
    case 'community':
      return SelectCommunityList
    case 'pageLink':
      return PageLink
  }
})
onMounted(() => {
  window.addEventListener(
    'message',
    res => {
      /**开发环境不校验发送方地址 */
      if (import.meta.env.MODE == 'development') {
        postMessageCallback(res)
      } else {
        if (origin == location.origin) {
          postMessageCallback(res)
        }
      }
    },
    false
  )
})
const data = reactive({})
const onConfirm = ids => {
  const query = {
    type: postMessageType.value,
    data: {} as any,
  }
  if (postMessageType.value == 'pageLink') {
    Object.assign(query.data, ids)
  } else {
    query.data = {
      ids: ids.join(','),
      list: cloneDeep(list.value),
    }
  }

  sendPostMessage(query)
}
</script>
<template>
  <div class="page">
    <iframe ref="iframeRef" :src="iframeUrl" name="receiverFrame" style="width: 100vw; height: 100vh" />
    <component :is="cmp" v-if="store.show" v-model:show="store.show" v-bind="bindOptions" v-model:list="list" v-model:data="data" @confirm="onConfirm" />
  </div>
</template>
<style lang="less" scoped>
.page {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}
</style>
